<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="900px"
      :before-close="cancel"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-card>
        <div slot="header">
          <span>用户环境变量</span>
        </div>
        <el-form
          :model="form.userForm"
          ref="userForm"
          class="demo-dynamic"
          :inline="true"
          size="mini"
          :disabled="flag"
        >
          <!-- path -->
          <el-row>
            <el-form-item label="追加到path" label-width="90px">
              <el-input
                style="width: 400px"
                v-model="form.userForm.domains[0].varValue"
              ></el-input>
            </el-form-item>
            <el-divider class="pathDivider"></el-divider>
          </el-row>
          <el-row>
            <el-form-item label=" " label-width="90px">
              <el-button @click="addDomain">新增变量</el-button>
            </el-form-item>
          </el-row>

          <div
            v-for="(domain, index) in form.userForm.domains"
            :key="domain.key"
          >
            <!-- 除path外变量 -->
            <div v-if="index !== 0">
              <el-form-item
                label="变量名称"
                label-width="90px"
                :prop="'domains.' + index + '.varName'"
                :rules="{
                  required: true,
                  validator: validateIsPathUser,
                  trigger: 'blur',
                }"
              >
                <el-input
                  style="width: 110px"
                  v-model="domain.varName"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="值"
                label-width="40px"
                :prop="'domains.' + index + '.varValue'"
                :rules="{
                  required: true,
                  message: '值不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input
                  style="width: 240px"
                  v-model="domain.varValue"
                ></el-input>
              </el-form-item>
              <el-form-item label=" " label-width="10px">
                <el-radio v-model="domain.varWay" label="追加">追加</el-radio>
                <el-radio v-model="domain.varWay" label="覆盖">覆盖</el-radio>
              </el-form-item>
              <el-button size="mini" @click.prevent="removeDomain(domain)"
                >删除</el-button
              >
            </div>
          </div>
        </el-form>
      </el-card>
      <el-card style="margin-top: 10px">
        <div slot="header">
          <span>系统环境变量</span>
        </div>
        <el-form
          :model="form.systemForm"
          ref="systemForm"
          class="demo-dynamic"
          :inline="true"
          size="mini"
          :disabled="flag"
        >
          <!-- path -->
          <el-row>
            <el-form-item label="追加到path" label-width="90px">
              <el-input
                style="width: 400px"
                v-model="form.systemForm.domains[0].varValue"
              ></el-input>
            </el-form-item>
            <el-divider class="pathDivider"></el-divider>
          </el-row>
          <el-row>
            <el-form-item label=" " label-width="90px">
              <el-button @click="addDomainSystem">新增变量</el-button>
            </el-form-item>
          </el-row>

          <div
            v-for="(domain, index) in form.systemForm.domains"
            :key="domain.key"
          >
            <!-- 除path外变量 -->
            <div v-if="index !== 0">
              <el-form-item
                label="变量名称"
                label-width="90px"
                :prop="'domains.' + index + '.varName'"
                :rules="{
                  required: true,
                  validator: validateIsPathSystem,
                  trigger: 'blur',
                }"
              >
                <el-input
                  style="width: 110px"
                  v-model="domain.varName"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="值"
                label-width="40px"
                :prop="'domains.' + index + '.varValue'"
                :rules="{
                  required: true,
                  message: '值不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input
                  style="width: 240px"
                  v-model="domain.varValue"
                ></el-input>
              </el-form-item>
              <el-form-item label=" " label-width="10px">
                <el-radio v-model="domain.varWay" label="追加">追加</el-radio>
                <el-radio v-model="domain.varWay" label="覆盖">覆盖</el-radio>
              </el-form-item>
              <el-button size="mini" @click.prevent="removeDomainSystem(domain)"
                >删除</el-button
              >
            </div>
          </div>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer" v-if="!flag">
        <el-button type="primary" @click="saveForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    flag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {
        userForm: {
          domains: [
            {
              varName: "path",
              varValue: "",
              varWay: "覆盖",
              dataType: "user",
            },
          ],
        },
        systemForm: {
          domains: [
            {
              varName: "path",
              varValue: "",
              varWay: "覆盖",
              dataType: "system",
            },
          ],
        },
      },
      // 弹窗控制
      open: false,
      // 弹窗标题
      title: "",
    };
  },
  methods: {
    // 打开环境变量录入弹窗
    openDialog(data) {
      this.title = "环境变量录入";
      this.open = true;
      // data 不为空 回显数据
      if (!this.validatenull(data)) {
        console.log("回显数据：", data);
        this.form = Object.assign({}, data);
      }
    },
    // 关闭弹窗
    cancel() {
      this.form = this.$options.data().form;
      this.open = false;
    },
    // 增加用户环境变量
    addDomain() {
      this.form.userForm.domains.push({
        key: Date.now(),
        varName: "",
        varValue: "",
        varWay: "覆盖",
        dataType: "user",
      });
    },
    // 删除用户环境变量
    removeDomain(item) {
      var index = this.form.userForm.domains.indexOf(item);
      if (index !== -1) {
        this.form.userForm.domains.splice(index, 1);
      }
    },
    // 增加系统环境变量
    addDomainSystem() {
      this.form.systemForm.domains.push({
        key: Date.now(),
        varName: "",
        varValue: "",
        varWay: "覆盖",
        dataType: "system",
      });
    },
    // 删除系统环境变量
    removeDomainSystem(item) {
      var index = this.form.systemForm.domains.indexOf(item);
      if (index !== -1) {
        this.form.systemForm.domains.splice(index, 1);
      }
    },
    // 检验值去空后是否为path
    validateIsPathUser(rule, value, callback) {
      const str = value.replace(/\s/g, "").toLowerCase();
      let flag = false;
      if (this.form.userForm.domains.length > 1) {
        const names = this.form.userForm.domains.map((it) =>
          it.varName.replace(/\s/g, "").toLowerCase()
        );
        if (names.filter((it) => it === str).length > 1) {
          flag = true;
        }
      }
      if (str === "path") {
        return callback(new Error("变量名称不能为path"));
      } else if (this.validatenull(str)) {
        return callback(new Error("变量名称不能为空"));
      } else if (flag) {
        return callback(new Error("变量名称不能重复"));
      } else {
        return callback();
      }
    },
    // 检验值去空后是否为path
    validateIsPathSystem(rule, value, callback) {
      const str = value.replace(/\s/g, "").toLowerCase();
      let flag = false;
      if (this.form.systemForm.domains.length > 1) {
        const names = this.form.systemForm.domains.map((it) =>
          it.varName.replace(/\s/g, "").toLowerCase()
        );
        if (names.filter((it) => it === str).length > 1) {
          flag = true;
        }
      }
      if (str === "path") {
        return callback(new Error("变量名称不能为path"));
      } else if (this.validatenull(str)) {
        return callback(new Error("变量名称不能为空"));
      } else if (flag) {
        return callback(new Error("变量名称不能重复"));
      } else {
        return callback();
      }
    },
    // 保存方法
    saveForm() {
      this.$refs["userForm"].validate((valid) => {
        if (valid) {
          this.$refs["systemForm"].validate((valid1) => {
            if (valid1) {
              this.$emit(
                "saveEnvVarForm",
                JSON.parse(JSON.stringify(this.form))
              );
              this.form = this.$options.data().form;
              this.open = false;
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.pathDivider {
  margin: 12px 0;
}
</style>
